<template>
  <div style="width:100%">
    <div v-if="isInChildren">
      <div v-for="item in valueArray" :key="item.id" class="wps_container">
        <div class="left">{{ item.name }}</div>
      </div>
    </div>
    <div v-else-if="isDesigner" class="wps_container">
      <el-button type="primary" plain class="ml-5">
        上传文件
      </el-button>
    </div>
    <div v-else-if="(!value && !multiple || multiple || hiddenList) && this.mixEditable" class="wps_container mb-10">
      <el-upload
        ref="upload"
        v-bind="$attrs"
        :disabled="!mixEditable"
        :headers="headers"
        listType="button"
        :accept="accept"
        :http-request="uploadFile"
        :on-success="success"
        :on-error="error"
        v-on="$listeners"
        :show-file-list="false"
        :multiple="multiple"
        :before-upload="beforeAvatarUpload"
      >
        <el-button type="primary">{{ btnName || '上传文件' }}</el-button> <span v-if="$attrs.infoText" class="infoText"> ({{ $attrs.infoText }})</span>
      </el-upload>
    </div>
    <div v-if="value && !hiddenList">
      <transition-group name="fade" tag="div">
        <div
          v-for="(attachment, index) in valueArray"
          :key="`attachment-${attachment.id}`"
          class="upload_item is-success">
          <div class="item_name">
              <img :src="getSrc(attachment)" alt="" class="svgicon">
              <span style="cursor:pointer;">{{ attachment.name }}</span>
          </div>
          <div class="item_des mr-10">{{ attachment.size }}</div>
          <div class="item_des mr-5">{{ attachment.time }}</div>
          <div class="action">
              <a @click="downloadServe(attachment)" class="ml-5" >下载</a>
              <a @click="previewApp(attachment)" class="ml-5">预览</a>
              <a v-if="index && mixEditable" class="ml-5" @click="sortUp(index)">上移</a>
              <a v-if="(index !== valueArray.length - 1) && mixEditable" class="ml-5" @click="sortDown(index)">下移</a>
              <a v-if="mixEditable" style="float: right;" class="ml-5" @click.stop="removeAttachment(attachment)">删除</a>
          </div>
      </div>
      </transition-group>
    </div>
  </div>
</template>
<script>
import routerContextPath from '../../mixins/router-context-path.js'
import { AjaxUtil } from "base/lib";
import moment from 'dayjs'
export default {
  name:'upload',
  mixins: [routerContextPath],
  props:{
    // fieldid,name,type
    value:'',
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    headers: {
      default: () => {},
    },
    isInChildren: {
      type: Boolean,
      default: false
    },
    fileName: {
      type: String,
      default: 'demo'
    },
    accept: {},
    fileSize: {},
    multiple: {
      type: Boolean,
      default: false
    },
    hiddenList: {
      type: Boolean,
      default: false
    },
    btnName: {
      type: String,
      default: ''
    },
    successMessage: {
      type: String,
      default: ''
    }
  },
  computed: {
    valueArray() {
      const arr = this.value && this.value.split(this.separate).map(i => {
        const obj = i.split('/')
        if (obj[3]) {
          console.log(!obj[3] ,obj[3],'obj[3]')
          console.log(moment(new Date(Number(obj[3]))),'moment(obj[3])')
          console.log(moment(new Date(Number(obj[3]))).format('YYYY-MM-DD HH:mm:ss'),"moment(obj[3]).format('YYYY-MM-DD HH:mm:ss')")
        }
        return {
          id: obj[0],
          name: obj[1],
          size: obj[2],
          time: !obj[3] ? '' : moment(new Date(Number(obj[3]))).format('YYYY-MM-DD HH:mm:ss')
        }
      }) || []
      console.log(arr,'==arr')
      return arr
    },
    isDesigner(){
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    dispatchProxy(){
      if (Vue.prototype.dispatchProxy) {
        return Vue.prototype.dispatchProxy(this)
      } else {
        return this.dispatch
      }
    },
  },
  data() {
    return {
      fileType: 'w',
      ofdId: '',
      downloadUrl: '',
      imgUrl: {
          excel: require('./images/EXCEL.svg'),
          image: require('./images/image.svg'),
          audio: require('./images/AUDIO.svg'),
          other: require('./images/other.svg'),
          pdf: require('./images/PDF.svg'),
          ppt: require('./images/PPT.svg'),
          txt: require('./images/TXT.svg'),
          video: require('./images/VIDEO.svg'),
          word: require('./images/word.svg'),
      },
      types: {
        isImage : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/png|jpg|jpeg|svg|gif|bmp/.test(fileType)) {
      return true
    }
    return false
  },
   isVideo : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/mp4|webm|ogv|ogg/.test(fileType)) {
      return true
    }
    return false
  },
   isText : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/txt|log|java|sql|sh|bat|js|html|vue|xml|json|yaml/.test(fileType)) {
      return true
    }
    return false
  },
  isExcel : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/xls|xlsx/.test(fileType)) {
      return true
    }
    return false
  },
  isAudio : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/mp3|wav|wmv/.test(fileType)) {
      return true
    }
    return false
  },
  isPdf : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/pdf/.test(fileType)) {
      return true
    }
    return false
  },
  isPpt : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/ppt|pptx/.test(fileType)) {
      return true
    }
    return false
  },
  isWord : (fileType) => {
    if (!fileType) {
      fileType = ''
    }
    fileType = fileType.toLowerCase()
    if (/doc|docx/.test(fileType)) {
      return true
    }
    return false
  },
      },
      separate: ':'
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
       console.log(val,'==val')
      }
    }
  },
  created(){
   
  },
  methods: {
    getType(name) {
      const append = name.slice(name.lastIndexOf('.') + 1)
      if (['docx' , 'doc' , 'dot' , 'wps' , 'wpt' , 'dotx' , 'docm' ,'dotm' , 'rtf' , 'uot' , 'mht' , 'mhtml' ,'htm' , 'html' , 'xml'].includes(append)) {
        return 'w'
      } else if (['xls' , 'xlt' , 'et' , 'ett' , 'xlsx' , 'xltx' ,'csv' , 'xlsm' , 'xltm' , 'xlsb' , 'uos'].includes(append)) {
        return 's'
      } else if (['pptx' , 'ppt' , 'pot' , 'potx' , 'pps' , 'ppsx' , 'dps' ,'dpt' , 'pptm' , 'potm' , 'ppsm' , 'uop'].includes(append)) {
        return 'p'
      } else if (['pdf', 'ofd'].includes(append)) {
        return 'f'
      } else if (['jpeg', 'jpg', 'png', 'gif', 'bmp', 'tif', 'tiff', 'svg', 'psd'].includes(append)) {
        return 'image'
      } else {
        return 'x'
      }
    },
    async previewApp(item = {}) {
      const user = localStorage.getItem('user')
      const {id, name} = item
      const type = this.getType(name)
      if (type === 'image') {
        AjaxUtil.ajax({
            responseType : 'blob',
            url: `/XFfileServer/fileDownload?id=${id}`,
            method: 'GET',
            data: {},
        }).then(resp => {
          let blob = new Blob([resp.data], {type: 'image/jpeg'});
          const imageUrl = URL.createObjectURL(blob);
          const image = new Image();
          image.src = imageUrl;
          const imgwindow = window.open(imageUrl);
          imgwindow.document.write(image.outerHTML);
        })
        AjaxUtil.config.responseType = "json";
        return
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkView, {
        fileId: id,
        type,
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=preview`)
      } else {
        this.$message.error(msg)
      }
    },
    removeAttachment(attachment) {
        this.$confirm('是否确定删除文件?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            const index = this.valueArray.findIndex((a) => a.id === attachment.id)
            if (index !== -1) {
                let valueList = this.value && this.value.split(this.separate)
                valueList.splice(
                    index,
                    1
                )
                this.$emit("input", valueList.join(this.separate))
            }
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
        }).catch(() => {
        });
        
    },
    sortUp(index) {
        const valueList = this.value.split(this.separate)
        const currRow = valueList.splice(index, 1)[0]
        valueList.splice(index - 1, 0, currRow)
        this.$emit('input', valueList.join(this.separate))

        const currObj = this.valueArray.splice(index, 1)[0]
        this.valueArray.splice(index - 1, 0, currObj)
    },
    sortDown(index) {
        const valueList = this.value.split(this.separate)
        const currRow = valueList.splice(index, 1)[0]
        valueList.splice(index + 1, 0, currRow)
        this.$emit('input', valueList.join(this.separate))

        const currObj = this.valueArray.splice(index, 1)[0]
        this.valueArray.splice(index + 1, 0, currObj)
    },
    async downloadServe ({id, name}) {
        // AjaxUtil.config.responseType = "blob";
        AjaxUtil.ajax({
            responseType : 'blob',
            // url: window.location.origin + `/XFfileServer/fileDownload?id=${id}`,
            url: `/XFfileServer/fileDownload?id=${id}`,
            method: 'GET',
            data: {},
        }).then(resp => {
        console.log(resp,'=======下载resp')
            let url = window.URL.createObjectURL(resp.data);  //生成文件流下载链接
            let a = document.createElement('a');      //创建一个a标签用来跳转
            a.href = url;                             // a标签 href  赋值 链接  
            a.download = name;                  //设置下载文件的文件名和文件格式
            document.body.appendChild(a);             //将标签DOM，放置页面
            a.click();                              
            window.URL.revokeObjectURL(url);     //释放 url 对象内存
            document.body.removeChild(a);
        })
        AjaxUtil.config.responseType = "json";
    },
    async editApp(item) {
      const user = localStorage.getItem('user')
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.getLinkEdit, {
        fileId: item.id,
        type: item.type || 'w',
        wThirdParams: JSON.parse(user).userName
      })
      const { msg, data, code } = resp.data
      if (code === 200) {
        window.open(`${this.contextPath}/index.html#/preview/office?openLink=${encodeURIComponent(data.link)}&type=edit`)
      } else {
        this.$message.error(msg)
      }
    },
    async uploadFile(file){
      let params=new FormData()
      const user = localStorage.getItem('user')
      params.append('attachments',file.file)
      // params.append('userName', JSON.parse(user).userName)
      AjaxUtil.ajax({
            // responseType : 'blob',
            // url: window.location.origin + `/XFfileServer/fileDownload?id=${id}`,
            url: `/XFfileServer/fileSaveOrUpdate?userName=${JSON.parse(user).userName}`,
            method: 'POST',
            data: params,
        }).then(resp => {
          resp.data.forEach(item => {
            const { id, name, size, createTime } = item
            let finalSize = (size/1000).toFixed(2)
            if (finalSize > 999) {
              finalSize = (finalSize/1000).toFixed(2) + 'MB'
            } else {
              finalSize = finalSize + 'kB'
            }
            let val = id + '/' + name + '/' + finalSize + '/' + new Date(createTime).getTime()
            console.log(item,'===item')
            if (this.multiple) {
              val = (this.value ? (this.value + this.separate) : '') + val
            }
            this.$emit('input', val)
            this.$emit('addFile', this.multiple ? resp.data : resp.data[0])
          })
          this.fileList = []
          this.$message({
              type: 'success',
              message: (typeof(this.successMessage) === 'string' ? this.successMessage : '') || '上传成功!'
          })
        })
        // AjaxUtil.config.responseType = "json";
    },
    // 根据id下载
    // downloadself(item) {
    //   // AjaxUtil.config.responseType = "blob";
    //   AjaxUtil.ajax({
    //     responseType : 'blob',
    //     // url: window.location.origin + `/XFfileServer/fileDownload?id=${fileId}`,
    //     url: `/XFfileServer/fileDownload?id=${fileId}`,
    //     method: 'GET',
    //     data: {},
    //   }).then(resp => {
    //   console.log(resp,'=======下载resp')
    //       let url = window.URL.createObjectURL(resp.data);  //生成文件流下载链接
    //       let a = document.createElement('a');      //创建一个a标签用来跳转
    //       a.href = url;                             // a标签 href  赋值 链接  
    //       a.download = fileName;                  //设置下载文件的文件名和文件格式
    //       document.body.appendChild(a);             //将标签DOM，放置页面
    //       a.click();                              
    //       window.URL.revokeObjectURL(url);     //释放 url 对象内存
    //       document.body.removeChild(a);
    //   })
    //   AjaxUtil.config.responseType = "json";
    // },
    async downloadFormat(item) {
      const { downloadId, routerKey } = item
      const user = localStorage.getItem('user')
      const data = {
        downloadId,
        routeKey: routerKey,
        userName: JSON.parse(user).userName,
        target: 'ofd',
        fileName: this.fileName
      }
      const resp = await this.dispatchProxy(Vue.prototype.Controllers.WPSController.operateDocumentResultDownload, data)
      if (!resp.error) {
        this.downloadUrl = resp.data.downloadUrl
        this.ofdId = resp.data.fileId
        this.openAction()
      }
    },
    error(err, file, fileList) {
      this.$emit('uploadError',{err, file, fileList})
    },
    success(response, file, fileList) {

    },
    getSrc(attachment) {
      console.log(attachment,'====attachment')
      const { name = '' } = attachment
      const fileType = name.slice(name.lastIndexOf('.') + 1)
        if (this.types.isImage(fileType)) {
            return this.imgUrl.image
        } else if (this.types.isVideo(fileType)) {
            return this.imgUrl.video
        } else if (this.types.isText(fileType)) {
            return this.imgUrl.txt
        } else if (this.types.isPdf(fileType)) {
            return this.imgUrl.pdf
        } else if (this.types.isExcel(fileType)) {
            return this.imgUrl.excel
        } else if (this.types.isAudio(fileType)) {
            return this.imgUrl.audio
        } else if (this.types.isPpt(fileType)) {
            return this.imgUrl.ppt
        } else if (this.types.isWord(fileType)) {
            return this.imgUrl.word
        } else {
            return this.imgUrl.other
        }
    },
    beforeAvatarUpload(file) {
        const isLtSize = file.size / 1024 / 1024 < this.fileSize
        if (!isLtSize) {
            this.$message.warning(`上传附件不能超过 ${this.fileSize}MB!`);
        }
        return isLtSize
    }
  }
}
</script>
<style lang="scss" scoped>
  .wps_container {
    display: flex;
    .left {
      flex: 1;
    }
    // .el-button {
    //   margin-left: 5px;
    // }
  }
  .upload_item {
    display: flex;
    .item_name {
      flex: 1;
    }
    .item_des {
      color: #999;
    }
  }
.upload_item:hover {
    background-color: #EAF0FF;
}
.fade-list-enter-active {
        opacity: 0;
        transform: translateY(100%);
        transition: all 0.3s;
    }
    .fade-list-enter-to {
        opacity: 1;
        transform: translateY(0);
    }
    .infoText {
      color: #999;
      font-size: 12px;
    }
</style>